Skip to main content
ICT
Lesson A12 - Iterations
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

F. The do-while Loop (Optional) page 8 of 18

  1. There are conditional looping situations where it is desirable to have the loop execute at least once, and then evaluate an exit expression at the end of the loop.

  2. The do-while loop allows you to do a statement first, and then evaluate an exit condition. The do-while loop complements the while loop that evaluates the exit expression at the top of the loop.

  3. The general form of a do-while loop is:

    do{
    statement;
    }while (expression);

  4. The flow of control for a do-while loop is illustrated:

  5. The following fragment of code will keep a running total of integers, terminated by a sentinel zero value.

    int number, total = 0;
    do{
      System.out.print("Enter an integer (0 to quit) --> ");
      number = in.readInt();
      total += number;
    }while (number != 0);

    In contrast to the while loop version, the do-while has the advantage of using only one input statement inside of the loop. Because the Boolean condition is at the bottom, you must pass through the main body of a do-while loop at least once.

  6. The same strategies used to develop while loops apply to do-while loops. Make sure you think about the following four sections of the loop: initialization, loop boundary, contents of the loop, and the state of variables after the loop.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.